package com.yoomiito.app.ui.goods;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
//import com.netease.demo.live.fragment.LiveBottomBar;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailAdapter;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailHeaderAdapter;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailRecommendAdapter;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailTitleAdapter;
import com.yoomiito.app.interf.BaseBottomBar;
import com.yoomiito.app.model.bean.GoodsDetail;
import com.yoomiito.app.model.bean.MultipleItem;
import com.yoomiito.app.model.home.FreeGoodsBuyInfo;
import com.yoomiito.app.ui.order.sureorder.shopcar.ShopCarActivity;
import com.yoomiito.app.present.goods.GoodsInfoPresenter;
import com.yoomiito.app.share.ui.GoodsShareActivity;
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.BaoPinBottomBar;
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.FindCouponBottomBar;
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.GiftBottomBar;
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.StarStoreBottomBar;
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.TaoBaoBottomBar;
import com.yoomiito.app.ui.anyview.goodsinfo.bottom.YouPinBottomBar;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.TouchUtils;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.dialog.FreeGoodsCouponDialog;
import com.yoomiito.app.widget.dialog.VIPTipDialog;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.router.Router;
import io.reactivex.Observable;

public class GoodsInfoActivity extends BaseActivity<GoodsInfoPresenter> {
    @BindView(R.id.layout_rcy)
    RecyclerView mRecyclerView;
    @BindView(R.id.shopCar)
    ImageView mShopCar;
    @BindView(R.id.show_new_flag)
    View mNewFlag;
    @BindView(R.id.bottomParent)
    FrameLayout mBottomContainer;

    public static final String GOODS_INFO_ACT = "goods_info_act";
    private List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    private GoodsDetailHeaderAdapter headerAdapter;
    private GoodsDetail detail = null;
    private List<GoodsDetail> mGoodsDetails = new ArrayList<>();
    private List<String> urls = new ArrayList<>();
    private GoodsDetailAdapter detailAdapter;
    private List<GoodsDetail> recommendGoods = new ArrayList<>();
    private GoodsDetailRecommendAdapter recommendAdapter;
    private String id;
    private int mGoodsType;
    private String mTypeId = "1";
    private int mBuyType = 0;  // 购买区别：   1：立即购买    0：领券购买
    private VIPTipDialog vipTipDialog;
    private int LiveType;
    private String shareEventId = "";
    private String productId;//零元购使用
    private FreeGoodsCouponDialog freeGoodsCouponDialog;
    private BaseBottomBar mBaseBottomBar;

    public static void toGoodsInfo(Context context, String id, int goodsType) {
        Intent intent = new Intent(context, GoodsInfoActivity.class);
        intent.putExtra(Constant.ID, id);
        intent.putExtra(Constant.TYPE, goodsType);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_goods_info;
    }

    @Override
    public GoodsInfoPresenter newP() {
        return new GoodsInfoPresenter(App.mAppConfig);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putSerializable(GOODS_INFO_ACT, detail);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        detail = (GoodsDetail) savedInstanceState.getSerializable(GOODS_INFO_ACT);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            detail = (GoodsDetail) savedInstanceState.getSerializable(GOODS_INFO_ACT);
        }
        id = getIntent().getStringExtra(Constant.ID);
        mGoodsType = getIntent().getIntExtra(Constant.TYPE, AllCode.TaoBao);// 请求数据区分
        //0元购
        if (mGoodsType == AllCode.FreeBuyGoods) {
            String[] str = id.split("&");
            id = str[0];
            productId = str[1];
            mBaseBottomBar = new FindCouponBottomBar(GoodsInfoActivity.this, App.mAppConfig.getIsLogin());
            mBaseBottomBar.addBottomBarListener((left, center, right) -> {
                if (left) {
                    showLoading();
                    getP().buyFreeGoods(id, String.valueOf(detail.getNum_iid()));
                }
            });
        }

//        LiveType = getIntent().getIntExtra(LiveBottomBar.LiveType, 0);

        initView();
        requestData();
    }

    //根据商品详情 获取到的商品类型 来添加底部button
    private void addBottomView() {
        if (detail.getGood_type() == 1) {//淘宝
            mBaseBottomBar = new TaoBaoBottomBar(GoodsInfoActivity.this, App.mAppConfig.getIsLogin());
            mBaseBottomBar.addBottomBarListener((left, center, right) -> {
                if (left) {//收藏
                    getP().addCollection(id);
                } else {
                    getP().delCollection(id);
                }
            });
        } else if (detail.getGood_type() == 2) {
            switch (detail.getProduct_type()) {//0 大礼包  1 礼包  2 爆品  3  优品
                case 0:
                case 1:
                    mBaseBottomBar = new GiftBottomBar(GoodsInfoActivity.this, App.mAppConfig.getIsLogin());
                    break;
                case 2:
                    mShopCar.setVisibility(View.VISIBLE);
                    mBaseBottomBar = new BaoPinBottomBar(GoodsInfoActivity.this, App.mAppConfig.getIsLogin());
                    mBaseBottomBar.addBottomBarListener((left, center, right) -> {
                        if (center) {//加入购物车
                            showLoading();
                            getP().addShopCar(detail.getNum_iid());
                        }
                    });
                    break;
//                case AllCode.AgentMall:
                case 3:
                    mBaseBottomBar = new YouPinBottomBar(GoodsInfoActivity.this, App.mAppConfig.getIsLogin());
                    break;
                case 5:
                    mBaseBottomBar = new StarStoreBottomBar(GoodsInfoActivity.this, App.mAppConfig.getIsLogin());
                    break;
                case AllCode.FreeBuyGoods:

                    break;
            }
        }
        if (mBaseBottomBar != null) {
            mBottomContainer.addView(mBaseBottomBar);
        }
    }

    private void requestData() {
        showLoading();
        switch (mGoodsType) {
            case AllCode.TaoBao:
                getP().getGoodsInfo(id, mTypeId);
//                getP().getRelatedGoods(id);
                break;
            case AllCode.BaoPin:
                mTypeId = "2";
                Observable.timer(600, TimeUnit.MILLISECONDS)//防止在9.0闪屏
                        .subscribe(aLong -> {
                            getP().getGoodsInfo(id, mTypeId);
                            if (App.mAppConfig.getIsLogin()) {
                                getP().getList(1);
                            }
                        });
                break;
            case AllCode.Gift:
            case AllCode.YouPin:
            case AllCode.NoShowYongJin:
            case AllCode.AgentMall:
            case AllCode.StarStore:
                mTypeId = "2";
                Observable.timer(600, TimeUnit.MILLISECONDS)//防止在9.0闪屏
                        .subscribe(aLong -> getP().getGoodsInfo(id, mTypeId));
                break;
            case AllCode.FreeBuyGoods:
                getP().getFreeGoodsInfo(id, productId);
                break;
        }
    }

    private void initView() {
        adapters.clear();
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(1, 1);
        viewPool.setMaxRecycledViews(2, 1);
        viewPool.setMaxRecycledViews(3, 10);
        viewPool.setMaxRecycledViews(MultipleItem.RECOMMEND, 10);

        DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager, false);
        mRecyclerView.setAdapter(delegateAdapter);

        initHeader();
        initTitle_1();
        initDetail();
        if (AllCode.TaoBao == mGoodsType) {
            //关联商品需求已砍
//            initTitle_2();
//            initRecommendGoods();
        }

        delegateAdapter.setAdapters(adapters);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            dismissLoading();
        }
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (mGoodsType == AllCode.BaoPin && AllCode.NotifyShopCarData.equals(eventMessage.getEventType())) {//刷新购物车数据
            getP().getList(1);
        }
        if (AllCode.LoginSuccess.equals(eventMessage.getEventType())) {//登录成功 返回商品详情的上一级
            this.finish();
        }
    }

    //需求已砍
    private void initRecommendGoods() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(2);
        gridLayoutHelper.setVGap(DensityUtil.dp2px(5));
        gridLayoutHelper.setHGap(DensityUtil.dp2px(5));
        gridLayoutHelper.setMargin(DensityUtil.dp2px(5), 0, DensityUtil.dp2px(5), 0);
        gridLayoutHelper.setAutoExpand(false);
        recommendAdapter = new GoodsDetailRecommendAdapter(this, gridLayoutHelper, recommendGoods);
        adapters.add(recommendAdapter);
        recommendAdapter.setItemClickListener(position -> {
            id = String.valueOf(recommendGoods.get(position).getNum_iid());
            RouterUtils.toGoodsDetail(GoodsInfoActivity.this, id, AllCode.TaoBao);
            GoodsInfoActivity.this.finish();
        });
    }

    private void initTitle_2() {//猜你喜欢
        GoodsDetailTitleAdapter titleAdapter = new GoodsDetailTitleAdapter(this, "");
        adapters.add(titleAdapter);
    }

    private void initDetail() {
        detailAdapter = new GoodsDetailAdapter(this, urls);
        adapters.add(detailAdapter);
    }

    private void initTitle_1() {//商品详情
        GoodsDetailTitleAdapter titleAdapter = new GoodsDetailTitleAdapter(this, "");
        adapters.add(titleAdapter);
    }

    private void initHeader() {
        LinearLayoutHelper layoutHelper = new LinearLayoutHelper();
        headerAdapter = new GoodsDetailHeaderAdapter(this, mGoodsDetails, layoutHelper);
        adapters.add(headerAdapter);
        headerAdapter.setOnClickListener(s -> {
//            Log.i("YOM","优惠券");
            if (App.mAppConfig.getIsLogin()) {
                RouterUtils.TaoBaoWithUrl(s);
            } else {
//                AllUtils.toLogin(GoodsInfoActivity.this, AllCode.LoginIn);
                LoginUtils.INSTANCE.toOneKeyLogin(this);
            }
        });
        headerAdapter.setShareClickListener(() -> {
            if (App.mAppConfig.getIsLogin()) {
                TouchUtils.onEvent(shareEventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent());
                RouterUtils.toShareGoods(GoodsInfoActivity.this, id, mGoodsType);
            } else {
//                AllUtils.toLogin(GoodsInfoActivity.this, AllCode.LoginIn);
                LoginUtils.INSTANCE.toOneKeyLogin(this);
            }
        });
    }

    //友盟埋点事件id
    private void setUMengPoint(int type) {

        switch (type) {
            case AllCode.TaoBao:
                shareEventId = "taobaoProductDetailPageShareClick";
                break;
            case AllCode.BaoPin:
                shareEventId = "hotProductDetailPageShareClick";
                break;
            case AllCode.Gift:
                shareEventId = "giftProductDetailPageShareClick";
                break;
        }
    }

    /**
     * @param detail
     */
    public void setGoodsInfo(GoodsDetail detail) {

        if (detail == null) {
            pullMarket("未知错误，请重试");
            return;
        }
        this.detail = detail;

        int handleGoodsType = AllCode.getGoodsType(detail.getGood_type(), detail.getProduct_type(), mGoodsType);
        if (handleGoodsType != -1) {
            mGoodsType = handleGoodsType;
            setUMengPoint(handleGoodsType);
        }
        headerAdapter.setGoodsType(mGoodsType);
        mGoodsDetails.clear();
        mGoodsDetails.add(detail);
        headerAdapter.notifyDataSetChanged();

//        //商品详情
        if (detail == null || detail.getDesc().size() == 0) {
            ((GoodsDetailTitleAdapter) adapters.get(1)).setNewTitle("");
            return;
        } else {
            ((GoodsDetailTitleAdapter) adapters.get(1)).setNewTitle("商品详情");
        }
        urls.addAll(detail.getDesc());
        detailAdapter.notifyDataSetChanged();

        addBottomView();
        mBaseBottomBar.updateInfo(detail);
        dismissLoading();
        //直播 购买商品 不显示佣金
//        if (LiveType == AllCode.NoShowYongJin) {
//            mBaseBottomBar.noShow();
//        }
    }

    @OnClick({R.id.back,R.id.shopCar})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.shopCar:
                if (App.mAppConfig.getIsLogin()) {
                    ShopCarActivity.start(GoodsInfoActivity.this);
                } else {
//                    AllUtils.toLogin(GoodsInfoActivity.this, AllCode.LoginIn);
                    LoginUtils.INSTANCE.toOneKeyLogin(this);
                }
                break;
        }
    }

    public void showNewFlag(boolean show) {
        mNewFlag.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    public void setRecommendGoods(List<GoodsDetail> details) {
        if (details == null || details.size() == 0) {
            ((GoodsDetailTitleAdapter) adapters.get(3)).setNewTitle("");
            return;
        } else {
            ((GoodsDetailTitleAdapter) adapters.get(3)).setNewTitle("猜你喜欢");
        }
        recommendGoods.clear();
        recommendGoods.addAll(details);
        recommendAdapter.notifyDataSetChanged();
    }

    public void buyFreeGoods(String url) {
        RouterUtils.TaoBaoWithUrl(url);
    }

    public void showFreeGoodsCouponDialog(FreeGoodsBuyInfo freeGoodsBuyInfo) {
        if (freeGoodsCouponDialog == null) {
            freeGoodsCouponDialog = new FreeGoodsCouponDialog(this);
            freeGoodsCouponDialog.setFreeGoodsBuyInfo(freeGoodsBuyInfo);
            freeGoodsCouponDialog.setOnViewClickListener(view -> {
                buyFreeGoods(freeGoodsBuyInfo.getSend_url());
            });
        }
        freeGoodsCouponDialog.show();
    }

    //不同等级 分享规则  淘宝商品分享需要授权
    private void shareGoods() {
        switch (mGoodsType) {
            case AllCode.TaoBao:
                if (UserInfoConfig.getRoleId() > Type.LevelType.VIP_0) {
                    RouterUtils.toShareGoods(GoodsInfoActivity.this, id, mGoodsType);
                    return;
                }
            case AllCode.BaoPin:
            case AllCode.YouPin:
            case AllCode.Gift:
//                if (UserInfoConfig.getRoleId() > 0) {
                Router.newIntent(this)
                        .to(GoodsShareActivity.class)
                        .putString(Constant.ID, id)
                        .putInt(Constant.TYPE, mGoodsType)
                        .launch();
                return;
//                }
//                break;
//            case AllCode.Gift:
//                if (UserInfoConfig.getRoleId() > 7) {
//                    Router.newIntent(this)
//                            .to(GoodsShareActivity.class)
//                            .putString(Constant.ID, id)
//                            .putInt(Constant.TYPE, mGoodsType)
//                            .launch();
//                    return;
//                }
//                break;
        }
        showVipTip();
    }

    private void showVipTip() {
        if (vipTipDialog == null) {
            vipTipDialog = new VIPTipDialog(this);
            vipTipDialog.setOnClickListener(v -> {
                RouterUtils.toMain(GoodsInfoActivity.this, 1);
                finish();
            });
        }
        vipTipDialog.show();
    }

    //商品下架处理
    public void pullMarket(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            YMToast.showText(msg);
        }

//        if (AllCode.FreeBuyGoods==mGoodsType){//通知零元购刷新数据
//            EventMessage eventMessage = new EventMessage();
//            eventMessage.setEventType(Constant.UPDATE_DATA);
//            eventMessage.setCode(AllCode.FreeBuyGoods);
//            EventBus.getDefault().postSticky(eventMessage);
//        }
        finish();
    }
}
